<?php
use Thenbsp\Wechat\OAuth\Client;
use Thenbsp\Wechat\Wechat\Jsapi;
use Thenbsp\Wechat\Wechat\AccessToken;

class WechatController extends Yaf_Controller_Abstract{
	
	public $request;
    public $response;
    public $view;
    public $session;
    public $config;
    public $signPackage;
	protected $fromuser="";
	public function init() {
		$this->view = $this->getView();
		$this->setViewpath(APP_PATH . '/modules/' . $this->getModuleName() . '/views');
        $this->initView();
        // 各模块静态文件位置
        $this->view->assign('static', '/static/' . strtolower($this->getModuleName()));
        $this->request = $this->getRequest();
        $this->session = Yaf_Session::getInstance();
        $this->response = $this->getResponse();
        //
        $this->view->assign('controller', $this->request->getControllerName());
        $this->view->assign('action', $this->request->getActionName());
        $this->config = Yaf_Registry::get('config');
		$this->_req = $this->getRequest();
		$this->redis = RedisDB::factory('game');
        // ini_set("display_errors", "On");
        // error_reporting(E_ALL | E_STRICT);
        //setcookie ( 'openid', "", time ()+86400, "/" );
        $openid =isset($_COOKIE['openid'])?$_COOKIE['openid']:''; 
        //$openid ="";
        /* $openid ='oLu-Lw6USjQNKO6jfPMo0ZOfM6Fk';
        $time = time()+60*60*24*7;//7days
		setcookie("openid",$openid,$time); */
		$config_obj=Yaf_Registry::get("config");
		$config_wechat=$config_obj->wechat->toArray();
		$config_database =$config_obj->database->config->toArray();
	    $appid =$config_wechat['appid'];
		$appsecret=$config_wechat['appsecret'];

		$client = new Client($appid, $appsecret);
        if(!$openid){
				$state = rand(1000, 9999);
				// 手动指定 state
				$client->setState($state);
		        $client->setScope('snsapi_userinfo');
				$code= $this->getRequest()->getQuery('code');//getPost
				$state =$this->getRequest()->getQuery('state');
		    	if(!$code) {
					$url=$client->getAuthorizeUrl();
				    header('Location: '.$url);
		            exit;
				}
				$accessToken = $client->getAccessToken($code,$state);
		        $userinfo = $accessToken->getUser();
		        $res_userinfo = $userinfo->toArray();
				if(is_array($res_userinfo)&& $res_userinfo){
					$openid = $res_userinfo['openid'];
					$nickname =$res_userinfo['nickname'];
					$language =$res_userinfo['language'];
					$city =$res_userinfo['city'];
					$province =$res_userinfo['province'];
					$country =$res_userinfo['country'];
					$headimgurl =$res_userinfo['headimgurl'];
					$nickname= preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $nickname);
					//保存数据库
					$prefix =$config_database['prefix'];
					$memberTable = new HbModel($prefix.'member');
					$user_sql ="SELECT count(*) as total  FROM gm_member WHERE fromuser='".$openid."'";
					$havecount=$memberTable->query($user_sql);
					if($havecount[0]['total']){
						//update
						$sqlArray = array();
						foreach($post as $key=>$value){
							 $sqlArray[] = "`{$key}`='{$value}'";
						}
						$sql = "update gm_member set ".implode(',',$sqlArray)." where fromuser='".$openid."'";
						$memberTable->query($sql);
					}else{
						$post =array(
							'fromuser'=>$openid,
							'nickname'=>$nickname,
							'language'=>$language,
							'province'=>$province,
							'country'=>$country,
							'city'=>$city,
							'headimgurl'=>$headimgurl,
							'create_date'=>date('Y-m-d H:i:s',time()),
						);
						$memberTable->add($post);
						$this->autoRegister($openid,$nickname,$headimgurl);
					}
					$time = time()+60*60*24*7;//7days
					setcookie("openid",$openid,$time);
				}
        }
        $mUser = new UserModel(null,false);
		$mUser->getUidByFromuser($openid);
		$user = $mUser->getInfo();
        $this->fromuser=$openid;
        $roomId =$_GET['roomId'];
        if($roomId){
        	$url="http://".$_SERVER['HTTP_HOST']."/game/index.html?roomId=".$roomId."&uid=".$openid;
			header('Location:'.$url);
			exit;
        }

  //       if(isset($user['roomid']) && $user['roomid']){
  //       		//获取房间信息
  //       		$roomInfo = $this->redis->hGetAll(ElephantajiangModel::INFO_KEY . $user['roomid']);
  //       		$created =$roomInfo['time'];//创建时间
  //       		$time_value =$roomInfo['time_value'];
  //       		$time_way =$roomInfo['time_way'];
  //       		if($time_way==1){
  //       			if(time() < $created+$time_value*60){
  //       				//file_put_contents('./library/users.txt', json_encode($roomInfo).PHP_EOL,FILE_APPEND);
		//         		$url="http://".$_SERVER['HTTP_HOST']."/game/index.html?roomId=".$user['roomid']."&uid=".$openid;
		// 				header('Location:'.$url);
		// 				exit;
  //       			}
  //       		}

        		
		// }	

	}

	private	function randUsername()
	{
		$str = '0123456789abcdefghijklnmopqrstuvwxyz';
		$len = strlen($str);
		$ret = '';
		for($i = 0; $i < 8; ++$i){
			$idx = mt_rand(0, $len - 1);
			$ret.= $str{$idx};
		}
		return $ret;
	}
	/**
	 * 自动注册
	 * [autoRegister description]
	 * @param  [type] $fromuser   [description]
	 * @param  [type] $nickname   [description]
	 * @param  [type] $headimgurl [description]
	 * @return [type]             [description]
	 */
	public function autoRegister($fromuser,$nickname,$headimgurl){
		$username =$fromuser;
		$nickname =$nickname?$nickname:$this->randUsername();
		$redis = RedisDB::factory('user');
		$uid = $redis->incr(UserModel::USERID_KEY);
		$ret = $redis->hSetNx(UserModel::USERNAME_KEY, $username, $uid);
		if(!$ret){
			
			return 'UserNameExists';
		}
		//write user info
		$user = array(
			'uid' => $uid,
			'username' => $username,
			'nickname' => $nickname,
			'point' => 0,
			'gold' => 100,//钻石
			'level'=>0,
			'headimgurl'=>$headimgurl,
			'paiju'=>0,//总局数
			'victory'=>0,//胜利
			'escape'=>0,//逃跑
			'regdate' => time(),
		);
		$redis->hMSet(UserModel::INFO_KEY . $uid, $user);
		$redis->hSetNx(UserModel::LIST_USER,$uid,json_encode($user));

		//write auth info
		$token = md5(date('YmdHis') . mt_rand(1000, 9999) . $username);
		$redis->hSet(UserModel::AUTH_KEY, $username, $token);
		//保存token
		$memberTable = new HbModel('gm_member');
		$sql="UPDATE gm_member  SET token='".$token."' WHERE fromuser='".$fromuser."'";
		$memberTable->execute($sql);
		return array(
				'username'=>$username,
				'token'=>$token,
			);
	}


	public function response_post($code,$message,$jsoncallback='',$data=NULL){
			$tmp_output="";
	        $tmp_output .= '<script>';
	        $tmp_output .= ( 'top.' . $jsoncallback . '(' . json_encode(array('code' => $code,'message' => $message,'data'=>$data,'server_time'=>time())) . ');');
	        $tmp_output .= '</script>';
	        echo $tmp_output;
	        exit;
		
	}
	public function response($code,$message,$data){
		$res_data =array(
					'code'=>$code,
					'message'=>$message,
					'data'=>$data,	
				);
			echo json_encode($res_data);
			exit;
	}
	public function http_get_data($url) {
		  
		$ch = curl_init ();  
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );  
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );  
		curl_setopt ( $ch, CURLOPT_URL, $url );  
		ob_start ();  
		curl_exec ( $ch );  
		$return_content = ob_get_contents ();  
		ob_end_clean ();  
		  
		$return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );  
		return $return_content;  
	}
	public function getip() {
		if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
			$ip = getenv("HTTP_CLIENT_IP");
		else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
			$ip = getenv("REMOTE_ADDR");
		else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
			$ip = $_SERVER['REMOTE_ADDR'];
		else
			$ip = "unknown";
		return ($ip);
	}
}